﻿
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Newtonsoft.Json;
using RestSharp;

//{"deletedeployment": {
//	"SubscriptionAlias":"SubscriptionA",
//	"Service":
//		{"ServiceName":"golive-wcfdataservice",
//		 "Slot":"production"}
//    }
//}

namespace wamr.Worker
{
    class DeleteDeploymentTask: ManagerTask
    {
        // input parameters
        private string _serviceName = "";
        private string _deploymentSlot = "";

        // retrieved from config settings
        private string _subscriptionID = "";
        private string _certificateThumbprint = "";

        private string requestID = string.Empty;
        private RestAPIHelper rest = null;

        public XNamespace wa = "http://schemas.microsoft.com/windowsazure";
        XNamespace ns1 = "http://www.w3.org/2001/XMLSchema-instance";

        public DeleteDeploymentTask(string ManagerMessage)
        {
            MessageIsValid = true;
            TaskType = "DeleteDeployment";

            JSONClasses.JSONDeleteDeploymentRootObject r = JsonConvert.DeserializeObject<JSONClasses.JSONDeleteDeploymentRootObject>(ManagerMessage);

            if (string.IsNullOrEmpty(r.deletedeployment.SubscriptionAlias) ||
                string.IsNullOrEmpty(r.deletedeployment.Service.ServiceName) ||
                string.IsNullOrEmpty(r.deletedeployment.Service.Slot))
            {
                MessageIsValid = false;
                Trace.TraceError("All parameters are required.");
                return;
            }

            _subscriptionID = CloudConfigurationManager.GetSetting(r.deletedeployment.SubscriptionAlias + ".SubscriptionID");
            _certificateThumbprint = CloudConfigurationManager.GetSetting(r.deletedeployment.SubscriptionAlias + ".CertificateThumbprint");

            _serviceName = r.deletedeployment.Service.ServiceName;
            _deploymentSlot = r.deletedeployment.Service.Slot;

        }

        public override bool PreConditionsMet()
        {
            TaskDisposition = TaskDispositionEnum.PROCEED;
            return true;
        }

        public override bool Initiate()
        {
            string uriFormat = "https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/{2}";
            Uri uri = new Uri(string.Format(uriFormat, _subscriptionID, _serviceName, _deploymentSlot));

            XDocument responseBody = null;

            try
            {
                rest = new RestAPIHelper(_certificateThumbprint);
            }
            catch (ArgumentNullException)
            {
                Trace.TraceError("The certificate thumbprint is incorrect.");
                TaskDisposition = TaskDispositionEnum.FAIL;
                return false;
            }

            try
            {
                requestID = rest.InvokeRequest(uri, "DELETE", HttpStatusCode.Accepted, null, out responseBody);
            }
            catch (ApplicationException ex)
            {
                if (responseBody != null)
                {
                    XElement xError = responseBody.Element(wa + "Error");
                    XElement xCode = xError.Element(wa + "Code");
                    if (xCode.Value == "TooManyRequests")
                    {
                        TaskDisposition = TaskDispositionEnum.WAIT;
                        return true;
                    }
                }
                Trace.TraceError(ex.Message);
                TaskDisposition = TaskDispositionEnum.FAIL;
                return false;
            }

            TaskDisposition = TaskDispositionEnum.PROCEED;
            return true;
        }

        public override void ResolveDependency()
        {
            // there are no dependencies for this task type so just...
            return;
        }

        public override bool Status()
        {
            string uriFormat = "https://management.core.windows.net/{0}/operations/{1}";
            Uri uri = new Uri(String.Format(uriFormat, _subscriptionID, requestID));
            XDocument responseBody;
            rest.InvokeRequest(uri, "GET", HttpStatusCode.OK, null, out responseBody);

            XElement xe = responseBody.Element(wa + "Operation");
            RestAPIHelper.OperationStatus status = (RestAPIHelper.OperationStatus)Enum.Parse(typeof(RestAPIHelper.OperationStatus), xe.Element(wa + "Status").Value);
            if (status == RestAPIHelper.OperationStatus.Succeeded)
                TaskDisposition = TaskDispositionEnum.COMPLETE;
            else if (status == RestAPIHelper.OperationStatus.Failed || status == RestAPIHelper.OperationStatus.TimedOut)
                TaskDisposition = TaskDispositionEnum.FAIL;

            return true;
        }


    }
}
